package com.ydzt.fanka.server.space.transmit;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.BufferRecord;
import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.persistence.BufferStore;
import com.ydzt.fanka.server.utils.ByteConvert;
import com.ydzt.fanka.server.utils.FileUtil;
import com.ydzt.fanka.server.utils.IOUtil;
import com.ydzt.fanka.server.utils.XmlUtil;

public class MultiPackage {
	static Logger logger = Logger.getLogger(MultiPackage.class.getName());
	private static BufferRecord bufferRecord = null;
	private static String bufferID = null;
	public synchronized static boolean getPackageToTransmit(){
		bufferRecord = new BufferRecord();
		bufferID = UUID.randomUUID().toString();
		bufferRecord.setBufferId(bufferID);
		int fileLength = 0;
		int headLength = 23;
		boolean flag = false;
		int tmp = 0;
		int currentSize = 0;
		int oneRecordLength = 0;
		int waitPkglength = 0;
		byte[] waitSendPkg = null;
		byte[] flagPkg = new byte[1];
		flagPkg[0] = 0x01;
		byte[] agm = new byte[1];
		agm[0] = 0x01;
		byte[] msgMgrType = new byte[1];
		msgMgrType[0] = 0x03;
		try{
			File f = new File(InitData.transmitPath);
			File AllMsgTypeDir[] = f.listFiles();
			for(int i = 0;i < AllMsgTypeDir.length;i ++){
				File oneMsgTypeDir = f.listFiles()[i];
				int offset = 0;
				while(oneMsgTypeDir.listFiles().length != 0){
					oneRecordLength = XmlUtil.GetRootNodeAttributeLength(InitData.paramDefineFile + "/" + oneMsgTypeDir.getName() + ".xml");
					File paramlist[] = oneMsgTypeDir.listFiles();
					int count = paramlist.length;
					currentSize += headLength;
					for(;tmp < count; tmp ++){
						fileLength = (int)paramlist[tmp].length();
						if(fileLength != 0){
							currentSize += (paramlist[tmp].length() - headLength);
							if(currentSize > Integer.parseInt(InitData.pkgLength)){
								currentSize = currentSize - ((int)paramlist[tmp].length() - headLength);
								break;
							}
						}
						else{
							logger.error("发现transmit中有长度为0的坏包");
						}
					}
					waitPkglength = currentSize;
					logger.info("对  " + tmp + "个报文进行拼接    拼接后的包长度为:" + waitPkglength);
					waitSendPkg = new byte[waitPkglength];
					byte[] msgType = new byte[2];
					msgType = ByteConvert.str2BcdNormal(oneMsgTypeDir.getName());
					//System.out.println(LoggerFanka.dumpBin(waitSendPkg));
					System.arraycopy(msgType, 0, waitSendPkg, offset, 2);
					offset += 2;
					System.arraycopy(ByteConvert.str2BcdNormal(InitData.nodeType + "000000"), 0, waitSendPkg, offset, 4);
					offset += 4;
					System.arraycopy(ByteConvert.str2BcdNormal("00000000"), 0, waitSendPkg, offset, 4);
					offset += 4;
					int port = 0;
					/*
					if(Integer.parseInt(InitData.center_port) > 32767){
						port = Integer.parseInt(InitData.center_port) - 65536;
					}
					else{
						port = Integer.parseInt(InitData.center_port);
					}
					*/
					System.arraycopy(ByteConvert.shortToBytes((short)port), 0, waitSendPkg, offset, 2);
					offset += 2;
					System.arraycopy(msgMgrType, 0, waitSendPkg, offset, 1);
					offset += 1;
					System.arraycopy(ByteConvert.intToBytes(12344321), 0, waitSendPkg, offset, 4);
					offset += 4;
					System.arraycopy(ByteConvert.shortToBytes((short) 1), 0, waitSendPkg, offset, 2);
					offset += 2;
					System.arraycopy(flagPkg, 0, waitSendPkg, offset, 1);
					offset += 1;
					//System.out.println("count-->offset:" + offset);
					//System.out.println(LoggerFanka.dumpBin(waitSendPkg));
					short pkgCount = (short) ((waitPkglength - headLength) / oneRecordLength);
					System.arraycopy(ByteConvert.shortToBytes(pkgCount), 0, waitSendPkg, offset, 2);
					offset += 2;
					//System.out.println("agm-->offset:" + offset);
					//System.out.println(LoggerFanka.dumpBin(waitSendPkg));
					System.arraycopy(agm, 0, waitSendPkg, offset, 1);
					offset += 1;
					for (int j = 0; j < tmp; j++) {
						File paramFile = paramlist[j];
						if(paramFile.length() != 0){
							try {
								byte[] content = IOUtil
										.toByteArrayTraditional(paramFile
												.getAbsolutePath());
								System.arraycopy(content, headLength, waitSendPkg, offset,
										content.length - headLength);
								offset += content.length - headLength;
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
					bufferRecord.setBufferContent(waitSendPkg);
					if(BufferStore.writePackageIntoWaitTransmit(bufferRecord) == 0){
						for (int k = 0; k < tmp; k++) {
							paramlist[k].delete();
						}
						flag = true;
					}
					else{
						//写入失败 但是文件是被创建成功的 故删除写入失败的空文件
						FileUtil.deleteWaitTransmit(bufferRecord);
					}
					currentSize = 0;
					tmp = 0;
					offset = 0;
				}
			}
		}
		catch(Exception e){
			logger.error(e.getMessage(), e);
			
		}
		return flag;
	}
}
